package cn.etgps.etgps.ui;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.jcodecraeer.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.etgps.etgps.R;
import cn.etgps.etgps.adapter.VehicleListAdapter;
import cn.etgps.etgps.base.MyBasicActivity;
import cn.etgps.etgps.dataEntity.VehicleDetailBean;
import cn.etgps.etgps.dataEntity.VehicleInfoBean;
import cn.etgps.etgps.dialog.DialogCreater;
import cn.etgps.etgps.event.EventExpenseEntity;
import cn.etgps.etgps.event.EventOilLogEntitiy;
import cn.etgps.etgps.event.EventReceiveEntity;
import cn.etgps.etgps.event.EventSendEntity;
import cn.etgps.etgps.mvp.Traffic_Iview;
import cn.etgps.etgps.mvp.Traffic_Presenter;
import cn.etgps.etgps.port.VehicleListPort;
import cn.etgps.etgps.utils.CommonUtils;
import cn.etgps.etgps.utils.T;

/**
 * Created by xiaoyu on 2016/3/28.+
 * 行车日志
 */
public class TrafficActivity extends MyBasicActivity<Traffic_Presenter> implements Traffic_Iview, VehicleListPort {
    private final int pageCount = 15;
    @Bind(R.id.traffic_log_plate_num)
    TextView plateNum;
    @Bind(R.id.traffic_log_et_driver)
    EditText driverName;
    @Bind(R.id.traffic_log_et_brand)
    TextView textBrand;
    @Bind(R.id.traffic_log_is_send)
    TextView tagIsSend;
    @Bind(R.id.traffic_log_is_receive)
    TextView tagIsReceive;
    @Bind(R.id.traffic_log_et_travel)
    TextView textTravel;
    @Bind(R.id.traffic_log_is_oil)
    TextView tagIsOil;
    @Bind(R.id.traffic_log_is_expense)
    TextView tagIsExpense;
    @Bind(R.id.traffic_log_plate_layout)
    LinearLayout plateLayout;
    private String vidStr, vehicleTypeNameStr, driverNameStr, kmilStr;
    private int page = 1;
    private ListPopup listPopup;
    private boolean isFirst = true;
    private boolean hasSend = false, hasReceive = false, hasOil = false, hasExpense = false, hasPlate = false;
    private EventSendEntity sendEntity;
    private EventReceiveEntity receiveEntity;
    private EventOilLogEntitiy oilLogEntitiy;
    private EventExpenseEntity eventExpenseEntity;

    @Override
    protected void setTitle() {
        titleBar.setLeftImageResource(R.mipmap.nav_back);
        titleBar.setLeftText(" ");
        titleBar.setTitle(getResources().getString(R.string.label_traffic_log));
    }

    @Override
    protected void initPresenter() {
        super.initPresenter();
        mPresenter = new Traffic_Presenter(this, this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_traffic_log;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        EventBus.getDefault().register(this);
        listPopup = new ListPopup(mContext);
        initData();
    }

    private void initData() {
        mPresenter.onRequestVehicleInfo(true, page, pageCount);
    }

    private void loadData() {
        mPresenter.onRequestVehicleInfo(false, page, pageCount);
    }

    @OnClick({R.id.traffic_log_plate_layout, R.id.traffic_log_send_item, R.id.traffic_log_receive_item,
            R.id.traffic_log_oil_item, R.id.traffic_log_expense_item, R.id.traffic_log_save})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.traffic_log_plate_layout:
                if (listPopup != null) {
                    listPopup.dismiss();
                    listPopup.showAsDropDown(plateLayout);
                }
                break;
            case R.id.traffic_log_send_item:
                TrafficSendActivity.gotoTrafficSendActivity(this, sendEntity);
                break;
            case R.id.traffic_log_receive_item:
                TrafficReceiveActivity.gotoTrafficReceiveActivity(this, receiveEntity);
                break;
            case R.id.traffic_log_oil_item:
                TrafficOilLogActivity.gotoTrafficOilLogActivity(this, oilLogEntitiy, vidStr);
                break;
            case R.id.traffic_log_expense_item:
                TrafficExpenseActivity.gotoTrafficExpenseActivity(this, eventExpenseEntity);
                break;
            case R.id.traffic_log_save:
                if (checkOk()) {
                    showNormalDialog(DialogCreater.DIALOG_PROGRESS);
                    mPresenter.onSaveVehicleRunLog(vidStr, vehicleTypeNameStr, driverNameStr, kmilStr, sendEntity,
                            receiveEntity, oilLogEntitiy, eventExpenseEntity);
                }
                break;
        }
    }

    private boolean checkOk() {
        driverNameStr = driverName.getText().toString().trim();
        kmilStr = textTravel.getText().toString().trim();
        vehicleTypeNameStr = textBrand.getText().toString().trim() + "";
        if (!hasPlate) {
            T.showShort(mContext, "请选择车牌号");
            return false;
        }
        if (CommonUtils.isEmpty(driverNameStr)) {
            T.showShort(mContext, "请输入姓名");
            return false;
        }
        if (!hasSend) {
            T.showShort(mContext, "请填写发车记录");
            return false;
        }
        if (!hasReceive) {
            T.showShort(mContext, "请填写收车记录");
            return false;
        }
        if (CommonUtils.isEmpty(kmilStr)) {
            T.showShort(mContext, "请输入行驶里程");
            return false;
        }
        if (!hasOil) {
            T.showShort(mContext, "请填写用油记录");
            return false;
        }
        return true;
    }

    @Override
    public void onSetInfoEntity(VehicleInfoBean.ContentBean contentBean) {
        String plateNumStr = contentBean.getLicense();
        if (!TextUtils.isEmpty(plateNumStr)) {
            hasPlate = true;
            vidStr = String.valueOf(contentBean.getVID());
            plateNum.setText(plateNumStr);
            if (listPopup != null) {
                listPopup.dismiss();
            }
            mPresenter.onGetVehicleDetail(vidStr);

        }
    }

    @Override
    public void onRefreshComplete(boolean isRefresh) {
        if (listPopup != null) {
            listPopup.refreshEnd(isRefresh);
        }
    }

    @Override
    public void onBindData(boolean isRefresh, List<VehicleInfoBean.ContentBean> data) {
        if (isFirst) {
            if (data.size() > 0) {
                String plateNumStr = data.get(0).getLicense();
                if (!TextUtils.isEmpty(plateNumStr)) {
                    vidStr = String.valueOf(data.get(0).getVID());
                    plateNum.setText(plateNumStr);
                    hasPlate = true;
                    mPresenter.onGetVehicleDetail(vidStr);
                }
            }
            isFirst = false;
        }
        if (listPopup != null) {
            listPopup.onSetAdapterData(isRefresh, data);
        }
    }

    @Override
    public void onNext() {
        finish();
    }

    @Override
    public void onBindDetail(VehicleDetailBean.ContentEntity contentEntity) {
        if (contentEntity != null) {
            //      driverName.setText(contentEntity.getDriverName());
            textBrand.setText(contentEntity.getVehicleTypeName());

        }
    }

    //----------------------------eventBus接收事件start-------------------------------------
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSendEvent(EventSendEntity sendEntity) {
        if (sendEntity != null) {
            this.sendEntity = sendEntity;
            tagIsSend.setText("已填写");
            hasSend = true;
            if (this.receiveEntity != null) {
                int differ = Integer.valueOf(receiveEntity.getKmil()) - Integer.valueOf(sendEntity.getKmil());
                if (differ > 0) {
                    textTravel.setText(String.valueOf(differ));
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiveEvent(EventReceiveEntity receiveEntity) {
        if (receiveEntity != null) {
            this.receiveEntity = receiveEntity;
            tagIsReceive.setText("已填写");
            if (this.sendEntity != null) {
                int differ = Integer.valueOf(receiveEntity.getKmil()) - Integer.valueOf(sendEntity.getKmil());
                if (differ > 0) {
                    textTravel.setText(String.valueOf(differ));
                }

            }
            hasReceive = true;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onOilLogEvent(EventOilLogEntitiy oilLogEntitiy) {
        if (oilLogEntitiy != null) {
            this.oilLogEntitiy = oilLogEntitiy;
            tagIsOil.setText("已填写");
            hasOil = true;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onExpenseEvent(EventExpenseEntity eventExpenseEntity) {
        if (eventExpenseEntity != null) {
            this.eventExpenseEntity = eventExpenseEntity;
            tagIsExpense.setText("已填写");
            hasExpense = true;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //----------------------------eventBus接收事件end-------------------------------------
    class ListPopup extends PopupWindow {
        @Bind(R.id.vehicle_no_list)
        XRecyclerView recyclerView;
        VehicleListAdapter listAdapter;

        public ListPopup(Context context) {
            View view = LayoutInflater.from(context).inflate(R.layout.popup_list, null);
            ButterKnife.bind(this, view);
            setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
            setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            setFocusable(true);
            setOutsideTouchable(true);
            setBackgroundDrawable(new BitmapDrawable());
            setContentView(view);
            listAdapter = new VehicleListAdapter(context, TrafficActivity.this);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
            linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            recyclerView.setLayoutManager(linearLayoutManager);
            recyclerView.setPullRefreshEnabled(true);
            recyclerView.setLoadingMoreEnabled(true);
            recyclerView.setAdapter(listAdapter);
            recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
                @Override
                public void onRefresh() {
                    page = 1;
                    initData();
                }

                @Override
                public void onLoadMore() {
                    page++;
                    loadData();
                }
            });
            setOnDismissListener(new OnDismissListener() {
                @Override
                public void onDismiss() {
                    WindowManager.LayoutParams lp1 = getWindow().getAttributes();
                    lp1.alpha = 1.0f;
                    getWindow().setAttributes(lp1);
                }
            });
        }

        public void refreshEnd(boolean isRefersh) {
            if (isRefersh) {
                recyclerView.refreshComplete();
            } else {
                recyclerView.loadMoreComplete();
            }
        }

        public void onSetAdapterData(boolean isRefresh, List<VehicleInfoBean.ContentBean> data) {
            if (isRefresh) {
                listAdapter.addItemTop(data);
            } else {
                listAdapter.addItemLast(data);
            }
        }
    }
}
